# encoding: utf-8
"""
@author: 夏洛
@QQ: 1972386194
@file: 2-图像.py
"""

from io import BytesIO

import random
from PIL import Image, ImageDraw, ImageFont


def get_iamge():

    width, height, font_size, font_num = 300, 100, 48, 5
    bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 背景颜色
    image = Image.new(mode='RGB', size=(width, height), color=bg_color) # 画布
    draw = ImageDraw.Draw(image, mode='RGB')     # 绘图类
    font = ImageFont.truetype("C:\Windows\Fonts\Arial.ttf", font_size)  # 字体
    verify = str()
    for i in range(font_num):
        x = random.randint(i * (width / font_num), (i + 1) * (width / font_num) - font_size)
        y = random.randint(0, height - font_size)
        char = random.choice([chr(alpha) for alpha in range(65, 91)] + [str(num) for num in range(10)]) # 随机参数拼接给verify
        verify += char
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.text((x, y), char, fill=color, font=font)

    by = BytesIO()
    image.save(by,format='PNG')
    image_by = by.getvalue()
    return verify,image_by

from flask import Flask, Response, make_response
app = Flask(__name__)
@app.route('/')
def index():
    # text 保留在后端做对比使用  img 返回给前端做一个展示给客户看的
    text,img = get_iamge()
    resp = make_response(img)
    resp.content_type = "image/png"
    return resp

if __name__ == '__main__':
    app.run()


'''
后台生成图片 以及文本
图片用ocr识别到文字 
在把文字携带给后台 就能过验证码

会把客户传的 字母转大写 与自己生成的文本 转大写 进行对比

'''

